package com.example.demo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.security.KeyPair;
import java.util.Date;

public class JwtHelper {
  public static String JWT_HEAD_NAME = "Authorization";
  private static KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.ES256);
  private static long activityTime = 1000 * 60 * 60 * 24; // ms  1 day

  public static String createToken(String username) {
    return createToken(username, new Date(System.currentTimeMillis() + activityTime));
  }

  public static String createToken(String username, Date endDate) {
    String compact =
        Jwts.builder()
            .setSubject(username)
            .setIssuedAt(new Date())
            .setExpiration(endDate)
            .signWith(keyPair.getPrivate())
            .compact();
    return compact;
  }

  public static Claims parseToken(String token) {
    if (token == null || token.isEmpty()) return null;
    Jws<Claims> jws =
        Jwts.parserBuilder().setSigningKey(keyPair.getPublic()).build().parseClaimsJws(token);
    return jws.getBody();
  }

  public static boolean checkVaild(Claims claims) {
    if (claims == null) return false;
    if (claims.getExpiration().before(new Date())) {
      return false;
    }
    return true;
  }
}
